package com.hq.fxh.No5_User.MyModle;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;

import com.hq.fxh.CustomerView.CirclePageIndicator;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Modle.UploadImgRes;
import com.hq.fxh.No0_ChengQu.Activity.BaseActivity;
import com.hq.fxh.No5_User.MyModle.Activity.item.BannerAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.BigAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.CardAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.GraphicAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.QQAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.QRCodeAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.StoreAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.TiePianAdItem;
import com.hq.fxh.No5_User.MyModle.Activity.item.ToastUtils;
import com.hq.fxh.No5_User.MyModle.Model.CommonRes;
import com.hq.fxh.No5_User.MyModle.Model.GetAdvertByUidRes;
import com.hq.fxh.No5_User.MyModle.Model.GetWebUrlRes;
import com.hq.fxh.No5_User.MyModle.Model.WebBean;
import com.hq.fxh.R;
import com.hq.fxh.Utils.ImageUtils;
import com.hq.fxh.Utils.ScreenUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;
import com.lyft.android.scissors.CropView;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;


/**
 * @author 大圣
 * @ClassName AdEditorActivity
 * @Description : 广告模板编辑页面
 * @Created 16/5/18
 * @Email qwqe601660957@163.com
 */
public class AdEditorActivity extends BaseActivity implements AdTemplateAdapter.OnClickListener {
    private static final String picKey = "picKey";
    private static final int AD_EDIT = 10;
    private static final int AD_EDIT_BOTTOM = 11;
    /**
     * 悬浮
     */
//    private SwitchButton sbSuspend;
//    private TextView tvSuspend;
    //    private boolean isSuspend;//是否悬浮（0：否 1：是）
    private TextView tvRight;
    private RadioGroup rgAd;
    private RecyclerView recyclerView;
    private AdTypeRecAdapter adTypeRecAdapter;
    private AppCompatRadioButton rbHeadAd;
    private AppCompatRadioButton rbBottomAd;
    private AppCompatRadioButton rbTiePianAd;
    /**
     * 顶部广告
     */
    private LinearLayout llHead;
    /**
     * 底部广告
     */
    private LinearLayout llFoot;
    /**
     * 顶部广告
     */
    TextView addHeadAd;
    private AdTypeAdapter adTypeAdapterHead;
    private ViewPager viewPagerHead;
    private CirclePageIndicator pageIndicatorHead;
    private AdTemplateAdapter adTemplateAdapterHead;
    /**
     * 底部广告
     */
    private ViewPager viewPager;
    private CirclePageIndicator pageIndicator;
    private AdTypeAdapter adTypeAdapter;
    private AdTemplateAdapter adTemplateAdapter;
    private List<AdBannerInfo> adInfos;
    /**
     * 当前底部广告模板
     */
    private int currentAd;
    private long curFootId;
    /**
     * 当前顶部广告模板
     */
    private int currentAdHead;
    private long curTopId;
    private int isHead;// 1顶部 ； 2底部； 3贴片
    private int way;
    private int uid;
    private GetAdvertByUidRes.DataBean adData;
    private int isActive;
    private TextView addBusinessAd;
    private TextView isForceTop;
    private TextView isForseBottom;
    private LinearLayout ll_top;
    private List<AdBannerInfo> bottomList;
    private List<AdBannerInfo> topList;
    private boolean isBottom;
    private int isCompany;
    private String[] names;
    private int[] types;
    private int[] ids;
    private ProgressDialog progressDialog;
    /**
     * 贴片广告
     */
    private ViewPager viewPagerTiePian;
    private AdTemplateAdapter adTemplateAdapterTiePian;
    private LinearLayout llTiePian;
    private boolean isShowTiePianAd = true;
    private boolean isHaveBigBanner;
    private List<AdBannerInfo> bigbusList;
    private int bigAdCount;
    private List<WebBean> webBean = new ArrayList<>();
    private LinearLayout layout_Modle_back;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ad_editor;
    }

    @Override
    protected void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        rgAd = (RadioGroup) findViewById(R.id.rgAd);
        rbHeadAd = (AppCompatRadioButton) findViewById(R.id.rbHeadAd);
        rbBottomAd = (AppCompatRadioButton) findViewById(R.id.rbBottomAd);
        rbTiePianAd = (AppCompatRadioButton) findViewById(R.id.rbTiePianAd);
        llHead = (LinearLayout) findViewById(R.id.llHead);
        llFoot = (LinearLayout) findViewById(R.id.llFoot);
        llTiePian = (LinearLayout) findViewById(R.id.llTiePian);
        layout_Modle_back = (LinearLayout) findViewById(R.id.layout_Modle_back);

        addHeadAd = (TextView) findViewById(R.id.addHeadAd);
        viewPagerHead = (ViewPager) findViewById(R.id.viewPagerHead);
        viewPagerTiePian = (ViewPager) findViewById(R.id.viewPagerTiePian);
        pageIndicatorHead = (CirclePageIndicator) findViewById(R.id.pageIndicatorHead);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        pageIndicator = (CirclePageIndicator) findViewById(R.id.pageIndicator);
        tvRight = (TextView) findViewById(R.id.tvRight);
        addBusinessAd = (TextView) findViewById(R.id.addBusinessAd);
        isForceTop = (TextView) findViewById(R.id.isForceTop);
        isForseBottom = (TextView) findViewById(R.id.isForseBottom);
        ll_top = (LinearLayout) findViewById(R.id.ll_top);
        initListenter();
    }

    private void initListenter() {
        layout_Modle_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        isActive = SharedPreferenceUtils.getIs_active(AdEditorActivity.this);
        isCompany = SharedPreferenceUtils.getIsCompany(AdEditorActivity.this);
        SharedPreferenceUtils sharedPreferenceUtils = new SharedPreferenceUtils(AdEditorActivity.this);
        uid = sharedPreferenceUtils.getMemberId();
        uid = 14227;
        isCompany = 1;
        setTitle("编辑我的广告");
        getSpaceImagePersionCardUrl();
/*
        toolbar.setNavigationIcon(getResources().getDrawable(R.mipmap.back_white));
*/
        currentAd = 0;
        currentAdHead = 0;
        way = 0;
        isHead = 2;
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("保存");
        adTypeAdapter = new AdTypeAdapter(AdEditorActivity.this);
        adTypeAdapterHead = new AdTypeAdapter(AdEditorActivity.this);

        adInfos = new ArrayList<>();
        adTemplateAdapter = new AdTemplateAdapter(AdEditorActivity.this, adInfos);
        adTemplateAdapterHead = new AdTemplateAdapter(AdEditorActivity.this, new ArrayList<AdBannerInfo>());
        adTemplateAdapterTiePian = new AdTemplateAdapter(AdEditorActivity.this, new ArrayList<AdBannerInfo>());
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            currentAd = bundle.getInt(Config.POSITION, 0);
            currentAdHead = bundle.getInt(Config.AD_HEAD_POSITION, 0);
            curTopId = bundle.getLong(Config.CUR_TOP_ID, 0);
            curFootId = bundle.getLong(Config.CUR_FOOT_ID, 0);
            way = bundle.getInt(Config.WAY, 0);
            if (bundle.get("isShowTiePianAd") != null) {
                isShowTiePianAd = bundle.getBoolean("isShowTiePianAd");
            }
        }
        if (way == 1) {
            isHead = 1;
        } else if (way == 0) {
            isHead = 2;
        } else if (way == 2) {
            isHead = 3;
        }
        initRecyclerView();

        if (isCompany == 1) {
            addBusinessAd.setVisibility(View.VISIBLE);
            names = new String[]{"企业模板", "大图通栏", "名片广告", "通栏广告", "店铺广告", "二维码广告", "QQ广告"};
            types = new int[]{Config.AdTypeCode.AD_BANNER, Config.AdTypeCode.AD_BIG_BANNER, Config.AdTypeCode.AD_CARD, Config.AdTypeCode.AD_BANNER, Config.AdTypeCode.AD_Store, Config.AdTypeCode.AD_QR_CODE, Config.AdTypeCode.AD_QQ};
            ids = new int[]{R.mipmap.tu_tubiao, R.mipmap.datu, R.mipmap.mingp, R.mipmap.tonglan, R.mipmap.dianpu, R.mipmap.erweima, R.mipmap.gg_qq};
        } else if (isCompany == 0) {
            addBusinessAd.setVisibility(View.GONE);
            names = new String[]{"大图通栏", "名片广告  ", "通栏广告  ", "店铺广告", "二维码广告", "QQ广告"};
            types = new int[]{Config.AdTypeCode.AD_BIG_BANNER, Config.AdTypeCode.AD_CARD, Config.AdTypeCode.AD_BANNER, Config.AdTypeCode.AD_Store, Config.AdTypeCode.AD_QR_CODE, Config.AdTypeCode.AD_QQ};
            ids = new int[]{R.mipmap.datu, R.mipmap.mingp, R.mipmap.tonglan, R.mipmap.dianpu, R.mipmap.erweima, R.mipmap.gg_qq};
        }
        List<AdType> lists = new ArrayList<>();
        for (int i = 0; i < names.length; i++) {
            AdType adType = new AdType();
            adType.setName(names[i]);
            adType.setType(types[i]);
            adType.setIcon(ids[i]);
            lists.add(adType);
        }
        adTypeRecAdapter.addData(lists);
        AdType adType = new AdType();
        adType.setType(types[0]);
        adType.setName("通栏广告");
        adTypeAdapter.addAll(lists);
        adTypeAdapterHead.add(adType);
        viewPagerHead.setAdapter(adTemplateAdapterHead);
        viewPagerTiePian.setAdapter(adTemplateAdapterTiePian);
        pageIndicatorHead.setViewPager(viewPagerHead);
        pageIndicatorHead.setFillColor(getResources().getColor(R.color.new_red));
//        viewPager.setOffscreenPageLimit(1);
        viewPager.setAdapter(adTemplateAdapter);
        pageIndicator.setViewPager(viewPager);
        pageIndicator.setFillColor(getResources().getColor(R.color.new_red));
        registerListener();
        getMerchantTempletList();
        initIsShowTiePianAd();
        swichTab(way);
    }

    private void getSpaceImagePersionCardUrl() {
        UserServiceImpl.getWebUrl(uid + "", new NetworkSubscriber<GetWebUrlRes>() {
            @Override
            public int onSuccess(GetWebUrlRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
                    webBean.addAll(data.getData());
                    for (int i = 0; i < webBean.size(); i++) {
                        if (webBean.get(i).getCode().equals("card")) {
                            String spaceImgURL = webBean.get(i).getUrl();
                            SharedPreferenceUtils.setSpaceImageUrl(AdEditorActivity.this, spaceImgURL);
                        }
                    }
                } else {
                    ToastUtils.show(AdEditorActivity.this, data.getMsg());
                }
                return 0;
            }
        });
    }

    private void initIsShowTiePianAd() {
        if (isShowTiePianAd) {//显示贴片广告
            rbTiePianAd.setVisibility(View.VISIBLE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                rbHeadAd.setBackground(getResources().getDrawable(R.drawable.bg_rb_middle_red_white));
            }
            llTiePian.setVisibility(View.VISIBLE);
        } else {//不显示贴片广告
            rbTiePianAd.setVisibility(View.GONE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                rbHeadAd.setBackground(getResources().getDrawable(R.drawable.bg_rb_my_half_right));
            }
            llTiePian.setVisibility(View.GONE);
        }
    }

    private void initTiePianAd() {
        AdBannerInfo adBannerInfo = new AdBannerInfo();
        adBannerInfo.setIs_carousel(1);//是否显示
        adBannerInfo.setAdvert_postion(0);
        adBannerInfo.setAdvert_type_id(Config.AdTypeCode.AD_TiePian);
        adBannerInfo.setAdvert_detail(new AdBannerInfo.AdvertDetailBean());
        adTemplateAdapterTiePian.add(adBannerInfo);
        viewPagerTiePian.setCurrentItem(0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JAnalyticsInterface.onPageStart(this, "我的模板");
    }

    public void initRecyclerView() {
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new SpacesItemDecoration(ScreenUtils.dip2px(AdEditorActivity.this, 15)));
        adTypeRecAdapter = new AdTypeRecAdapter(this);
        recyclerView.setAdapter(adTypeRecAdapter);
    }


    public void registerListener() {
        addBusinessAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isActive == 1) {
                    if (adTemplateAdapterHead != null && adTemplateAdapterHead.getCount() >= 10) {
                        ToastUtils.show(AdEditorActivity.this, "最多添加10个广告模板");
                        return;
                    } else {
                        toBusinessTempActivity(false);//顶部企业模板
                    }
                } else if (isActive == 0) {
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁顶部广告模板");
                }
            }
        });

        rgAd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.rbHeadAd:
                        way = 1;
                        isHead = 1;
                        swichTab(way);
                        break;
                    case R.id.rbBottomAd:
                        isHead = 2;
                        way = 0;
                        swichTab(way);
                        break;
                    case R.id.rbTiePianAd:
                        isHead = 3;
                        swichTab(2);//tiepian
                        break;
                }

            }
        });
        addHeadAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 顶部广告模板添加 */

                if (isActive == 1) {
                    if (adTemplateAdapterHead != null && adTemplateAdapterHead.getCount() == 10) {
                        ToastUtils.show(AdEditorActivity.this, "最多添加10个广告模板");
                        return;
                    } else {
                        AdBannerInfo adInfo = null;
                        AdBannerInfo adBannerInfo = new AdBannerInfo();
                        adBannerInfo.setIs_carousel(1);
                        adBannerInfo.setAdvert_postion(2);
                        adBannerInfo.setAdvert_type_id(Config.AdTypeCode.AD_BANNER);
                        adInfo = adBannerInfo;
                        adTemplateAdapterHead.add(adInfo);
                        viewPagerHead.setCurrentItem(adTemplateAdapterHead.getCount() - 1);
                    }
                } else if (isActive == 0) {
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁顶部广告模板");
                }
            }
        });


        adTypeRecAdapter.setOnRecyclerViewItemClickListener(new BaseRecAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, int position) {

                if (adTemplateAdapter != null && adTemplateAdapter.getCount() > 0 && adTemplateAdapter.getItem(0).getAdvert_type_id() == Config.AdTypeCode.AD_BIG_BANNER) {
                    isHaveBigBanner = true;//有大图通栏
                    bigAdCount = 1;
                } else {
                    isHaveBigBanner = false;
                    bigAdCount = 0;
                }

                /** 底部广告模板添加 */
                if (isActive == 1) {
                    if (isCompany == 1 && position == 0) {
                        toBottomBusinessTempActivity();//底部企业模板
                    } else if (isCompany == 1 && position == 1 && isHaveBigBanner) {
                        ToastUtils.show(AdEditorActivity.this, "大图通栏广告最多只可以编辑一个");
                        viewPager.setCurrentItem(0);
                        return;
                    } else if (isCompany == 0 && position == 0 && isHaveBigBanner) {
                        ToastUtils.show(AdEditorActivity.this, "大图通栏广告最多只可以编辑一个");
                        viewPager.setCurrentItem(0);
                        return;
                    } else {
                        if (adTemplateAdapter != null && adTemplateAdapter.getCount() - bigAdCount >= 10) {
                            ToastUtils.show(AdEditorActivity.this, "最多添加10个广告模板");
                            return;
                        } else {
                            int type = adTypeRecAdapter.getItem(position).getType();
                            AdBannerInfo adInfo = null;
                            adInfo = new AdBannerInfo();
                            adInfo.setIs_carousel(1);
                            adInfo.setAdvert_postion(1);
                            adInfo.setAdvert_type_id(type);
                            if (type == Config.AdTypeCode.AD_BIG_BANNER) {
                                adTemplateAdapter.add(adInfo, 0);
                                viewPager.setCurrentItem(0);
                            } else {
                                adTemplateAdapter.add(adInfo);
                                viewPager.setCurrentItem(adTemplateAdapter.getCount() - 1);
                            }
                        }
                    }

                } else if (isActive == 0) {//未激活（企业版都是激活用户）
                    if (position == 0) {
                        ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁大图通栏广告模板");
                        return;
                    } else {
                        if (adTemplateAdapter != null && adTemplateAdapter.getCount() >= 2) {
                            ToastUtils.show(AdEditorActivity.this, "最多添加2个广告模板");
                            return;
                        } else {
                            int type = adTypeRecAdapter.getItem(position).getType();
                            AdBannerInfo adInfo = null;
                            adInfo = new AdBannerInfo();
                            adInfo.setIs_carousel(1);
                            adInfo.setAdvert_postion(1);
                            adInfo.setAdvert_type_id(type);
                            adTemplateAdapter.add(adInfo);
                            viewPager.setCurrentItem(adTemplateAdapter.getCount() - 1);
                        }
                    }
                }
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentAd = position;
                currentView = adTemplateAdapter.getView(position);
                curFootId = adTemplateAdapter.getItem(position).getAdvert_id();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPagerHead.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentAdHead = position;
                currentView = adTemplateAdapterHead.getView(position);
                curTopId = adTemplateAdapterHead.getItem(position).getAdvert_id();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateAdTemplate();
            }
        });
        adTemplateAdapter.setOnClickListener(this);
        adTemplateAdapterHead.setOnClickListener(this);
        adTemplateAdapterTiePian.setOnClickListener(this);
    }

    int count;

    private void toBottomBusinessTempActivity() {
        Bundle bundle = new Bundle();
        if (adTemplateAdapter != null && adTemplateAdapter.getCount() > 0 && adTemplateAdapter.getItem(0).getAdvert_type_id() == Config.AdTypeCode.AD_BIG_BANNER) {//有大图
            count = adTemplateAdapter.getCount() - 1;
        } else {
            count = adTemplateAdapter.getCount();
        }
        bundle.putInt("bottomCount", count);
        //     IntentUtils.openActivityForResult(AdEditorActivity.this, ToBottomBusinessTempActivity.class, AD_EDIT_BOTTOM, bundle);
    }

    private void toBusinessTempActivity(Boolean isbottom) {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isbottom", isbottom);
        bundle.putInt("topCount", adTemplateAdapterHead.getCount());
//        bundle.putInt("bottomCount", adTemplateAdapter.getCount());
        //    IntentUtils.openActivityForResult(AdEditorActivity.this, ToBusinessTempActivity.class, AD_EDIT, bundle);
    }

 /*   public void swichTab(int code) {
        switch (code) {
            case 0:
                *//** 底部广告 *//*
                rgAd.check(rbBottomAd.getId());
                llHead.setVisibility(View.GONE);
                llFoot.setVisibility(View.VISIBLE);
                llTiePian.setVisibility(View.GONE);
                rbHeadAd.setTextColor(getResources().getColor(R.color.white));
                rbTiePianAd.setTextColor(getResources().getColor(R.color.white));
                rbBottomAd.setTextColor(getResources().getColor(R.color.new_red));
                break;

            case 1:
                *//** 顶部广告 *//*
                if (isActive == 1) {//已激活
                    rgAd.check(rbHeadAd.getId());
                    llHead.setVisibility(View.VISIBLE);
                    llFoot.setVisibility(View.GONE);
                    llTiePian.setVisibility(View.GONE);
                    rbHeadAd.setTextColor(getResources().getColor(R.color.new_red));
                    rbBottomAd.setTextColor(getResources().getColor(R.color.white));
                    rbTiePianAd.setTextColor(getResources().getColor(R.color.white));
                } else {
                    swichTab(0);
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁顶部广告模板");
                }
                break;

            case 2:
                */

    /**
     * 贴片广告
     *//*
                if (isActive == 1) {//已激活
                    rgAd.check(rbTiePianAd.getId());
                    llHead.setVisibility(View.GONE);
                    llFoot.setVisibility(View.GONE);
                    llTiePian.setVisibility(View.VISIBLE);
                    rbTiePianAd.setTextColor(getResources().getColor(R.color.new_red));
                    rbHeadAd.setTextColor(getResources().getColor(R.color.white));
                    rbBottomAd.setTextColor(getResources().getColor(R.color.white));
                } else {
                    swichTab(0);
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁贴片广告模板");
                }
                break;

            default:
                swichTab(0);
                break;
        }
    }*/
    public void swichTab(int code) {
        switch (code) {
            case 0:
                /** 底部广告 */
                rgAd.check(rbBottomAd.getId());
                llHead.setVisibility(View.GONE);
                llFoot.setVisibility(View.VISIBLE);
                llTiePian.setVisibility(View.GONE);
                rbHeadAd.setTextColor(getResources().getColor(R.color.red));
                rbTiePianAd.setTextColor(getResources().getColor(R.color.red));
                rbBottomAd.setTextColor(getResources().getColor(R.color.white));
                rbTiePianAd.setBackgroundResource(R.drawable.style_switchbth_right);
                rbBottomAd.setBackgroundResource(R.drawable.style_switchbth_left_on);
                rbHeadAd.setBackgroundResource(R.drawable.style_switchbth_center);
                break;

            case 1:
                /** 顶部广告 */
                if (isActive == 1) {//已激活
                    rgAd.check(rbHeadAd.getId());
                    llHead.setVisibility(View.VISIBLE);
                    llFoot.setVisibility(View.GONE);
                    llTiePian.setVisibility(View.GONE);
                    rbHeadAd.setTextColor(getResources().getColor(R.color.white));
                    rbBottomAd.setTextColor(getResources().getColor(R.color.red));

                    rbTiePianAd.setTextColor(getResources().getColor(R.color.red));
                    rbTiePianAd.setBackgroundResource(R.drawable.style_switchbth_right);
                    rbBottomAd.setBackgroundResource(R.drawable.style_switchbth_left);
                    rbHeadAd.setBackgroundResource(R.drawable.style_switchbth_center_on);


                } else {
                    swichTab(0);
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁顶部广告模板");
                }
                break;

            case 2:
                /**贴片广告*/
                if (isActive == 1) {//已激活
                    rgAd.check(rbTiePianAd.getId());
                    llHead.setVisibility(View.GONE);
                    llFoot.setVisibility(View.GONE);
                    llTiePian.setVisibility(View.VISIBLE);
                    rbTiePianAd.setTextColor(getResources().getColor(R.color.white));
                    rbHeadAd.setTextColor(getResources().getColor(R.color.red));
                    rbBottomAd.setTextColor(getResources().getColor(R.color.red));
                    rbTiePianAd.setBackgroundResource(R.drawable.style_switchbth_right_on);
                    rbBottomAd.setBackgroundResource(R.drawable.style_switchbth_left);
                    rbHeadAd.setBackgroundResource(R.drawable.style_switchbth_center);
                } else {
                    swichTab(0);
                    ToastUtils.show(AdEditorActivity.this, "请先购买激活产品来解锁贴片广告模板");
                }
                break;

            default:
                swichTab(0);
                break;
        }
    }

    /**
     * 获取模板列表
     */
    public void getMerchantTempletList() {
        if (uid != 0) {
            UserServiceImpl.getAdTemp(uid + "", new NetworkSubscriber<GetAdvertByUidRes>() {
                @Override
                public int onSuccess(GetAdvertByUidRes data) {
                    super.onSuccess(data);
                    if (data != null && data.getCode() == 0) {
                        adData = data.getData();
                        int ifForceBottom = adData.getIs_force_bottom();
                        int ifForceTop = adData.getIs_force_top();

                        adTemplateAdapter.addAll(0, adData.getBottom());
                        adTemplateAdapterHead.addAll(0, adData.getTop());
                        adTemplateAdapterTiePian.addAll(0, adData.getVideo());
                        if (adData.getVideo() == null || adData.getVideo().size() == 0) {
                            initTiePianAd();
                        }
                        viewPager.setCurrentItem(currentAd);
                        viewPagerHead.setCurrentItem(currentAdHead);
                        viewPagerTiePian.setCurrentItem(0);

                        if (ifForceBottom == 0 && ifForceTop == 0) {//0可编辑  1 不可编辑
                            tvRight.setVisibility(View.VISIBLE);
                            isForceTop.setVisibility(View.GONE);
                            isForseBottom.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.VISIBLE);
                            ll_top.setVisibility(View.VISIBLE);
                        } else if (ifForceBottom == 1 && ifForceTop == 1) {
                            tvRight.setVisibility(View.GONE);
                            recyclerView.setVisibility(View.GONE);
                            ll_top.setVisibility(View.GONE);
                            isForceTop.setVisibility(View.VISIBLE);
                            isForseBottom.setVisibility(View.VISIBLE);
                        } else if (ifForceBottom == 0 && ifForceTop == 1) {
                            tvRight.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.VISIBLE);
                            ll_top.setVisibility(View.GONE);
                            isForceTop.setVisibility(View.VISIBLE);
                            isForseBottom.setVisibility(View.GONE);
                        } else if (ifForceBottom == 1 && ifForceTop == 0) {
                            tvRight.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                            ll_top.setVisibility(View.VISIBLE);
                            isForceTop.setVisibility(View.GONE);
                            isForseBottom.setVisibility(View.VISIBLE);
                        }
                    }
                    return 0;
                }
            });
        } else {
            //     IntentUtils.openActivity(AdEditorActivity.this, LoginActivity.class);
        }
    }

    private AdBannerInfo tiePianAd;
    private List<AdBannerInfo> emptyBannerAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyQRCodeAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyCardAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyGraphicAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyQQAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyStoreAdList = new ArrayList<>();
    private List<AdBannerInfo> emptyBigBannerList = new ArrayList<>();

    public void updateAdTemplate() {
        if (uid != 0) {
            List<AdBannerInfo> adInfoList = new ArrayList<>();
            List<AdBannerInfo> adInfos = adTemplateAdapter.getList();
            List<AdBannerInfo> headAds = adTemplateAdapterHead.getList();
            List<AdBannerInfo> tiePianAds = adTemplateAdapterTiePian.getList();
            if (adInfos != null && adInfos.size() > 0) {
                if (adInfos.get(0).getAdvert_type_id() == Config.AdTypeCode.AD_BIG_BANNER) {//有大图
                    if (adInfos.size() > 11) {
                        ToastUtils.show(AdEditorActivity.this, "最多添加10个底部模板");
                        return;
                    }
                } else {
                    if (adInfos.size() > 10) {
                        ToastUtils.show(AdEditorActivity.this, "最多添加10个底部模板");
                        return;
                    }
                }
            }
            if (headAds.size() > 10) {
                ToastUtils.show(AdEditorActivity.this, "最多添加10个顶部模板");
                return;
            }

            adInfoList.addAll(headAds);//顶部广告加入集合
            adInfoList.addAll(adInfos);//底部广告加入集合
            adInfoList.add(tiePianAds.get(0));
//            adInfoList.addAll(tiePianAds);//贴片广告加入集合

            AdBannerInfo info;
            String hintAdType = null;
            for (int i = 0; i < adInfoList.size(); i++) {
                info = adInfoList.get(i);
                if (info != null) {
                    int type = info.getAdvert_type_id();
                    int position = info.getAdvert_postion();////0 贴片 1 底部 2 顶部
                    if (type == Config.AdTypeCode.AD_BANNER) {//通栏
                        AdBannerInfo.AdvertDetailBean merchantArticleBannerModel = info.getAdvert_detail();
                        if (merchantArticleBannerModel == null) {
                            if (info != null) {
                                emptyBannerAdList.add(info);
                            }
                        } else {
                            if (TextUtils.isEmpty(merchantArticleBannerModel.getPic()) && TextUtils.isEmpty(merchantArticleBannerModel.getHref())) {//全为空
                                if (info != null) {
                                    emptyBannerAdList.add(info);
                                }
                            } else {//信息已填
                                String adtype;
                                if (position == 1) {
                                    adtype = "底部";
                                } else {
                                    adtype = "顶部";
                                }
                                if (TextUtils.isEmpty(merchantArticleBannerModel.getPic())) {
                                    hintAdType = adtype + "通栏广告的图片没有上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleBannerModel.getHref())) {
                                    hintAdType = adtype + "通栏广告的链接不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (merchantArticleBannerModel.getHref().contains("【")
                                        || merchantArticleBannerModel.getHref().contains("】")
                                        || merchantArticleBannerModel.getHref().contains("，")
                                        || merchantArticleBannerModel.getHref().contains("：")
                                        || merchantArticleBannerModel.getHref().contains("；")) {
                                    hintAdType = adtype + "通栏广告的链接格式不正确";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_QR_CODE) {//二维码
                        AdBannerInfo.AdvertDetailBean merchantArticleWechatModel = info.getAdvert_detail();
                        if (merchantArticleWechatModel == null) {
                            emptyQRCodeAdList.add(info);
                        } else {
                            if (TextUtils.isEmpty(merchantArticleWechatModel.getPic())
                                    && TextUtils.isEmpty(merchantArticleWechatModel.getDes())
                                    && TextUtils.isEmpty(merchantArticleWechatModel.getName())) {
                                if (info != null) {
                                    emptyQRCodeAdList.add(info);
                                }
                            } else {
                                if (TextUtils.isEmpty(merchantArticleWechatModel.getPic())) {
                                    hintAdType = "二维码广告的图片没有上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleWechatModel.getDes())) {
                                    hintAdType = "二维码广告的介绍不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleWechatModel.getName())) {
                                    hintAdType = "二维码广告的广告标语不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_CARD) {//名片
                        AdBannerInfo.AdvertDetailBean merchantArticleCardModel = info.getAdvert_detail();
                        if (merchantArticleCardModel == null) {
                            if (info != null) {
                                emptyCardAdList.add(info);
                            }
                        } else {
                            if (TextUtils.isEmpty(merchantArticleCardModel.getPic()) && TextUtils.isEmpty(merchantArticleCardModel.getName()) &&
                                    TextUtils.isEmpty(merchantArticleCardModel.getMobile()) && TextUtils.isEmpty(merchantArticleCardModel.getAddress())) {
                                if (info != null) {
                                    emptyCardAdList.add(info);
                                }
                            } else {
                                if (TextUtils.isEmpty(merchantArticleCardModel.getPic())) {
                                    hintAdType = "名片广告的图片没有上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleCardModel.getName())) {
                                    hintAdType = "名片广告的广告标语不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleCardModel.getMobile())) {
                                    hintAdType = "名片广告的手机号不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleCardModel.getAddress())) {
                                    hintAdType = "名片广告的广告介绍不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_GRAPHIC) {//图文
                        AdBannerInfo.AdvertDetailBean merchantArticleGraphicModel = info.getAdvert_detail();
                        if (merchantArticleGraphicModel == null) {
                            if (info != null) {
                                emptyGraphicAdList.add(info);
                            }
                        } else {
                            if (TextUtils.isEmpty(merchantArticleGraphicModel.getPic()) && TextUtils.isEmpty(merchantArticleGraphicModel.getName())
                                    && TextUtils.isEmpty(merchantArticleGraphicModel.getDes()) && TextUtils.isEmpty(merchantArticleGraphicModel.getHref())) {
                                if (info != null) {
                                    emptyGraphicAdList.add(info);
                                }
                            } else {
                                if (merchantArticleGraphicModel.getPic() == null) {
                                    hintAdType = "图文广告的图片没上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleGraphicModel.getName())) {
                                    hintAdType = "图文广告的广告标语不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleGraphicModel.getDes())) {
                                    hintAdType = "图文广告的广告介绍不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleGraphicModel.getHref())) {
                                    hintAdType = "图文广告的链接不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (merchantArticleGraphicModel.getHref().contains("【")
                                        || merchantArticleGraphicModel.getHref().contains("】")
                                        || merchantArticleGraphicModel.getHref().contains("，")
                                        || merchantArticleGraphicModel.getHref().contains("：")
                                        || merchantArticleGraphicModel.getHref().contains("；")) {
                                    hintAdType = "图文广告的链接不正确";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_QQ) {//qq
                        AdBannerInfo.AdvertDetailBean merchantArticleQQModel = info.getAdvert_detail();
                        if (merchantArticleQQModel == null) {
                            if (info != null) {
                                emptyQQAdList.add(info);
                            }
                        } else {
                            if (TextUtils.isEmpty(merchantArticleQQModel.getPic()) && TextUtils.isEmpty(merchantArticleQQModel.getName())
                                    && TextUtils.isEmpty(merchantArticleQQModel.getQQ()) && TextUtils.isEmpty(merchantArticleQQModel.getDes())) {
                                if (info != null) {
                                    emptyQQAdList.add(info);
                                }
                            } else {
                                if (merchantArticleQQModel.getPic() == null) {
                                    hintAdType = "QQ广告的图片没上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleQQModel.getName())) {
                                    hintAdType = "QQ广告的广告标语不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleQQModel.getQQ())) {
                                    hintAdType = "QQ广告的QQ号不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if (TextUtils.isEmpty(merchantArticleQQModel.getDes())) {
                                    hintAdType = "QQ广告的广告介绍不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_Store) {//店铺广告
                        AdBannerInfo.AdvertDetailBean store = info.getAdvert_detail();
                        AdBannerInfo.AdvertDetailBean.ProductInfoBean product = store.getProduct_info();
                        AdBannerInfo.AdvertDetailBean.OwnerInfoBean owner = store.getOwner_info();

                        if (TextUtils.isEmpty(product.getPic()) && TextUtils.isEmpty(product.getName()) && TextUtils.isEmpty(product.getPrice())
                                && TextUtils.isEmpty(product.getHref()) && TextUtils.isEmpty(owner.getPic()) && TextUtils.isEmpty(owner.getName())
                                && TextUtils.isEmpty(owner.getMobile())) {
                            if (info != null) {
                                emptyStoreAdList.add(info);
                            }
                        } else {
                            if (product.getPic() == null) {
                                hintAdType = "店铺广告的图片没上传或上传有误,请重试";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (TextUtils.isEmpty(product.getName())) {
                                hintAdType = "店铺广告的商品名称不能为空";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (TextUtils.isEmpty(product.getPrice())) {
                                hintAdType = "店铺广告的商品价格不能为空";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (TextUtils.isEmpty(product.getHref())) {
                                hintAdType = "店铺广告的链接不能为空";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (product.getHref().contains("【")
                                    || product.getHref().contains("】")
                                    || product.getHref().contains("，")
                                    || product.getHref().contains("：")
                                    || product.getHref().contains("；")) {
                                hintAdType = "店铺广告的商品图片没上传或上传有误,请重试";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (owner.getPic() == null) {
                                hintAdType = "店铺广告的店主图片上传有误,请重试";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (TextUtils.isEmpty(owner.getName())) {
                                hintAdType = "店铺广告的店铺名称不能为空";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                            if (TextUtils.isEmpty(owner.getMobile())) {
                                hintAdType = "店铺广告的联系电话不能为空";
                                AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                return;
                            }
                        }
                    } else if (type == Config.AdTypeCode.AD_TiePian) {//贴片广告
                        AdBannerInfo.AdvertDetailBean merchantArticleTiePianModel = info.getAdvert_detail();
                        if (merchantArticleTiePianModel == null) {
                            if (info != null) {
                                tiePianAd = info;
                            }

                        } else {
                            if (TextUtils.isEmpty(merchantArticleTiePianModel.getPic()) && TextUtils.isEmpty(merchantArticleTiePianModel.getHref())) {//全为空
                                if (info != null) {
                                    tiePianAd = info;
                                }

                            } else {
                                if (TextUtils.isEmpty(merchantArticleTiePianModel.getPic())) {
                                    hintAdType = "贴片广告的图片没上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleTiePianModel.getAction() != null ? merchantArticleTiePianModel.getAction() : 0) == 1 && TextUtils.isEmpty(merchantArticleTiePianModel.getHref())) {
                                    hintAdType = "贴片广告的链接不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleTiePianModel.getAction() != null ? merchantArticleTiePianModel.getAction() : 0) == 2 && TextUtils.isEmpty(merchantArticleTiePianModel.getHref())) {
                                    hintAdType = "贴片广告的电话不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleTiePianModel.getAction() != null ? merchantArticleTiePianModel.getAction() : 0) == 3 && TextUtils.isEmpty(merchantArticleTiePianModel.getHref())) {
                                    hintAdType = "贴片广告的QQ不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    } else if (type == Config.AdTypeCode.AD_BIG_BANNER) {//大图通栏广告
                        AdBannerInfo.AdvertDetailBean merchantArticleBigBannerModel = info.getAdvert_detail();
                        if (merchantArticleBigBannerModel == null) {
                            if (info != null) {
                                emptyBigBannerList.add(info);
                            }
                        } else {
                            if (TextUtils.isEmpty(merchantArticleBigBannerModel.getPic()) && TextUtils.isEmpty(merchantArticleBigBannerModel.getHref())) {//全为空
                                if (info != null) {
                                    emptyBigBannerList.add(info);
                                }
                            } else {
                                if (TextUtils.isEmpty(merchantArticleBigBannerModel.getPic())) {
                                    hintAdType = "大图通栏广告的图片没上传或上传有误,请重试";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleBigBannerModel.getAction() != null ? merchantArticleBigBannerModel.getAction() : 0) == 1 && TextUtils.isEmpty(merchantArticleBigBannerModel.getHref())) {
                                    hintAdType = "大图通栏广告的链接不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleBigBannerModel.getAction() != null ? merchantArticleBigBannerModel.getAction() : 0) == 2 && TextUtils.isEmpty(merchantArticleBigBannerModel.getHref())) {
                                    hintAdType = "大图通栏广告的电话不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                                if ((merchantArticleBigBannerModel.getAction() != null ? merchantArticleBigBannerModel.getAction() : 0) == 3 && TextUtils.isEmpty(merchantArticleBigBannerModel.getHref())) {
                                    hintAdType = "大图通栏广告的QQ不能为空";
                                    AdDialog(AdEditorActivity.this, position, i, headAds.size(), hintAdType);
                                    return;
                                }
                            }
                        }

                    }
                }
            }
            if (tiePianAd != null) {
                adInfoList.remove(tiePianAd);
            }
            if (emptyBannerAdList != null && emptyBannerAdList.size() > 0) {
                adInfoList.removeAll(emptyBannerAdList);
            }
            if (emptyQRCodeAdList != null && emptyQRCodeAdList.size() > 0) {
                adInfoList.removeAll(emptyQRCodeAdList);
            }
            if (emptyCardAdList != null && emptyCardAdList.size() > 0) {
                adInfoList.removeAll(emptyCardAdList);
            }
            if (emptyGraphicAdList != null && emptyGraphicAdList.size() > 0) {
                adInfoList.removeAll(emptyGraphicAdList);
            }
            if (emptyQQAdList != null && emptyQQAdList.size() > 0) {
                adInfoList.removeAll(emptyQQAdList);
            }
            if (emptyStoreAdList != null && emptyStoreAdList.size() > 0) {
                adInfoList.removeAll(emptyStoreAdList);
            }
            if (emptyBigBannerList != null && emptyBigBannerList.size() > 0) {
                adInfoList.removeAll(emptyBigBannerList);
            }
            progressDialog = ProgressDialog.show(AdEditorActivity.this, "", "加载中，请稍后……");
            progressDialog.setCancelable(true);//设置进度条是否可以按退回键取消
            progressDialog.setCanceledOnTouchOutside(true);//设置点击进度对话框外的区域对话框消失
            String json = new Gson().toJson(adInfoList);
//            json="[{\"advert_detail\":{\"href\":\"http://com.ledianduo.com/xxkj/index.html?MerchantId\\u003d14227\",\"pic\":\"http://imgs.ledianduo.com/app/ad/20170628143318636342571983511249.png\"},\"adTemplatePosition\":0,\"advert_id\":290508,\"advert_postion\":1,\"advert_type_id\":1,\"is_carousel\":1,\"member_id\":14227}]";
            UserServiceImpl.updateAdvert(uid + "", json, new NetworkSubscriber<CommonRes>() {
                @Override
                public int onSuccess(CommonRes data) {
                    super.onSuccess(data);
                    if (data != null && data.getCode() == 0) {
                        progressDialog.dismiss();
                        ToastUtils.show(AdEditorActivity.this, "保存成功");
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt(Config.POSITION, currentAd);
                        bundle.putInt(Config.AD_HEAD_POSITION, currentAdHead);
                        bundle.putLong(Config.CUR_TOP_ID, curTopId);
                        bundle.putLong(Config.CUR_FOOT_ID, curFootId);
                        intent.putExtras(bundle);
                        setResult(Config.ResultCode.AD_TEMPLATE_ADD, intent);
/*
                        EventBus.getDefault().post(new NotifyEvent(EventCode.REFRESH_AD_TEMPLATE));
*/
                        finish();
                    } else {
                        progressDialog.dismiss();
                        ToastUtils.show(AdEditorActivity.this, data.getMsg());
                    }
                    return 0;
                }
            });
        }
    }

    private void AdDialog(Activity activity, final int position, final int currentAdTemp, final int headSize, final String hintAd) {
////position 0 贴片 1 底部 2 顶部
        new AlertDialog.Builder(activity)
//                .setTitle("提示")//设置对话框标题
                .setMessage(hintAd)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        if (position == 1) {//1 底部
                            if (isHead != 2) {// 1顶部 ； 2底部； 3贴片
                                swichTab(0);//0底部 1顶部 2 贴片
                            }
                            viewPager.setCurrentItem(currentAdTemp - headSize);
                        } else if (position == 2) {//顶部
                            if (isHead != 1) {
                                swichTab(1);
                            }
                            viewPagerHead.setCurrentItem(currentAdTemp);
                        } else if (position == 0) {
                            if (isHead != 3) {
                                swichTab(2);
                            }
                            viewPagerTiePian.setCurrentItem(0);
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
            }
        }).show();//在按键响应事件中显示此对话框
    }

    private View currentView;

    @Override
    public void onClick(View v, int id, final int position) {
        switch (id) {
            case R.id.ibClose:
                /** 删除广告模板选项 */
                AlertDialog.Builder builder = new AlertDialog.Builder(AdEditorActivity.this);
                builder.setTitle("提示");
                builder.setMessage("确认删除吗?");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (isHead == 1) {
                            /** 删除广告模板选项 */
                            adTemplateAdapterHead.remove(adTemplateAdapterHead.getItem(currentAdHead));
                            viewPagerHead.setAdapter(null);
                            viewPagerHead.setAdapter(adTemplateAdapterHead);
                            currentAdHead = position;
                            if (adTemplateAdapterHead.getCount() == 1) {
                                currentAdHead = 0;
                            }
                            viewPagerHead.setCurrentItem(currentAdHead - 1 == -1 ? 0 : currentAdHead - 1);
                        } else if (isHead == 2) {//底部
                            /** 删除广告模板选项 */
                            adTemplateAdapter.remove(adTemplateAdapter.getItem(currentAd));
                            viewPager.setAdapter(null);
                            viewPager.setAdapter(adTemplateAdapter);
                            currentAd = position;
                            if (adTemplateAdapter.getCount() == 1) {
                                currentAd = 0;
                            }
                            viewPager.setCurrentItem(currentAd - 1 == -1 ? 0 : currentAd - 1);
                        }
                    }


//                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();

                break;
            case R.id.flAdPicAdd:
                if (isCompany == 1) {//0只显示拍照 相册，1 判断企业数据
                    openToChoosePic(1);
                } else {
                    openToChoosePic(2);
                }
                break;
            case R.id.flCardPicAdd:
                openToChoosePic(0);
                break;
            case R.id.flGraphicPicAdd:
                openToChoosePic(0);
                break;
            case R.id.flQRCodePicAdd:
                openToChoosePic(0);
                break;
            case R.id.flQQPicAdd:
                openToChoosePic(0);
                break;
            case R.id.goodsImg:
                resId = R.id.goodsImg;
                openToChoosePic(0);
                break;
            case R.id.shopImg:
                resId = R.id.shopImg;
                openToChoosePic(0);
                break;
            case R.id.flTiePIanPicAdd:
                openToChoosePic(0);
                break;
            case R.id.flBigPicAdd:
                openToChoosePic(0);
                break;
        }
    }

    int resId = -1;

//    public void delete(long type) {
//        if (uid != 0) {
//            DeleteMerchantTempletReq req = new DeleteMerchantTempletReq();
//            req.setMerchantId(CommonUtils.getUserId());
//            req.setMerchantTempletId(type);
//            Identity identity = CommonUtils.seetIdentity(this);
//            req.setIdentity(identity);
////            deleteMerchantTempletPresenter.deleteMerchantTemplet(req);
//
//
//        } else {
//            IntentUtils.openActivity(this, LoginActivity.class);
//        }
//
//
//    }

    /**
     * 选取图片弹窗
     */
    public void openToChoosePic(int type) {
//        ShowCutDialog();
        SoftInputUtils.hideSoftInput(this);
        ShowPickDialog(findViewById(R.id.main), type);
    }

    /**
     * 选取图片弹窗
     */
    private void ShowPickDialog(View v, int type) {
        LayoutInflater inflater = (LayoutInflater)
                this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.view_pick, null);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
        Button btnPick = (Button) view.findViewById(R.id.btnPick);//从相册选取
        Button btnPhoto = (Button) view.findViewById(R.id.btnPhoto);//拍照
        Button btnPicFromLocal = (Button) view.findViewById(R.id.btnPicFromLocal);
//        Button btnPicFromPro = (Button) view.findViewById(R.id.btnFreeDesign);
//        Button btnPerson = (Button) view.findViewById(R.id.btnPerson);
        Button btnCommon = (Button) view.findViewById(R.id.btnCommon);
        switch (type) {
            case 0:
                btnPicFromLocal.setVisibility(View.GONE);
//                btnPicFromPro.setVisibility(View.GONE);
//                btnPerson.setVisibility(View.GONE);
                btnCommon.setVisibility(View.GONE);
                break;
            case 1:
//                btnPicFromPro.setVisibility(View.VISIBLE);
//                btnPerson.setVisibility(View.VISIBLE);
                btnCommon.setVisibility(View.VISIBLE);
                btnPicFromLocal.setVisibility(View.VISIBLE);
                break;
            case 2:
//                btnPicFromPro.setVisibility(View.VISIBLE);
//                btnPerson.setVisibility(View.VISIBLE);
                btnCommon.setVisibility(View.VISIBLE);
                btnPicFromLocal.setVisibility(View.GONE);
                break;
        }
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setContentView(view);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.showAtLocation(v,
                Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, -1000);
//        btnPerson.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                IntentUtils.openActivityForResult(AdEditorActivity.this, PersionAdMaterialActivity.class, Config.RequestCode.TEMPLETE_CHOOSE);
//                popupWindow.dismiss();
//            }
//        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        btnCommon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //       IntentUtils.openActivityForResult(AdEditorActivity.this, AdCommonMaterialActivity.class, Config.RequestCode.TEMPLETE_CHOOSE);
                popupWindow.dismiss();
            }
        });
        btnPick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(),
                                "xiaoma.jpg")));
                startActivityForResult(intent, Config.GET_IMAGE_FROM_PICK);
            }
        });
        btnPicFromLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //         IntentUtils.openActivityForResult(AdEditorActivity.this, TempleteSourceNewActivity.class, Config.RequestCode.TEMPLETE_CHOOSE);
                popupWindow.dismiss();
            }
        });

        final String qqUrl = "mqqwpa://im/chat?chat_type=wpa&uin=2646607200&version=1";
//        btnPicFromPro.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                popupWindow.dismiss();
//                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)));
//            }
//        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(),
                                "xiaoma.jpg")));
                startActivityForResult(intent, Config.GET_IMAGE_FROM_TAKE_PHOTO);
                //有这个权限，做相应处理
//                PackageManager pm = getPackageManager();
//                boolean flag = (PackageManager.PERMISSION_GRANTED ==
//                        pm.checkPermission("android.permission.RECORD_AUDIO", "packageName"));
//                if (flag) {
//
//                }else {             //没有权限
//                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
//                    builder.setTitle("相机故障");
//                    builder.setMessage("相机权限被禁止,请开启");
//                }

            }
        });

    }

    private Bitmap currentBitmap = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {

            case Config.GET_IMAGE_FROM_PICK://98
                /** 相册获取 */
                if (data != null) {
                    final Uri uri = data.getData();
                    if (uri != null) {
                        /** 获取图片路径 */

                        String path = UriUtils.getImageAbsolutePath(this, uri);
                        Bitmap bitmap = null;
                        AdBannerInfo adInfo = null;
                        if (isHead == 1) {
                            adInfo = adTemplateAdapterHead.getItem(currentAdHead);
                        } else if (isHead == 2) {
                            if (adTemplateAdapter.getCount() == 1) {
                                currentAd = 0;
                            }
                            adInfo = adTemplateAdapter.getItem(currentAd);//// 1顶部 ； 2底部； 3贴片
                        } else if (isHead == 3) {
                            adInfo = adTemplateAdapterTiePian.getItem(0);
                        }
                        int type = adInfo.getAdvert_type_id();
                        if (type == Config.AdTypeCode.AD_BANNER) {
                            bitmap = ImageUtils.getSmallBitmap(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth / 4);
                            currentBitmap = bitmap;
                            ShowCutDialog();
                        } else if (type == Config.AdTypeCode.AD_TiePian) {
                            bitmap = ImageUtils.getSmallBitmap(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth * 14 / 25);
                            currentBitmap = bitmap;
                            ShowCutDialog();
                        } else if (type == Config.AdTypeCode.AD_BIG_BANNER) {
                            bitmap = ImageUtils.getSmallBitmap(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth * 2 / 5);
                            currentBitmap = bitmap;
                            ShowCutDialog();
                        } else {
//                            bitmap = ImageUtils.loadBigPic(path, ScreenUtils.dip2px(200), ScreenUtils.dip2px(200));
//                            bitmap = ImageUtils.zoomImg(bitmap, ScreenUtils.dip2px(200), ScreenUtils.dip2px(200));
                            bitmap = ImageUtils.getSmallBitmap(path, ScreenUtils.dip2px(AdEditorActivity.this, 200), ScreenUtils.dip2px(AdEditorActivity.this, 200));
                            int size = ImageUtils.getBitmapSize(bitmap);
//                            LogUtils.i("imageSize aaaa:" + size);
                            currentBitmap = bitmap;
                            ShowCutDialog();
//                            isPicked = true;
                        }
                    }
                }

//                String res = null;
//                String[] proj = { MediaStore.Images.Media.DATA };
//                Cursor cursor = getContentResolver().query(data.getData(), proj, null, null, null);
//                if(cursor.moveToFirst()){;
//                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                    res = cursor.getString(column_index);
//                }
//                cursor.close();
//                bitmap = BitmapFactory.decodeFile(res);
//                imageCut(srcPic.getTop());
                break;

            case 99:
                /** 拍照获取 */
                if (resultCode != 0) {
                    String path = Environment.getExternalStorageDirectory()
                            + "/xiaoma.jpg";

                    File temp = new File(path);
//               Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
//                        + "/xiaoma.jpg");

                    AdBannerInfo adInfo = null;
                    if (isHead == 1) {
                        adInfo = adTemplateAdapterHead.getItem(currentAdHead);
                    } else if (isHead == 2) {
                        if (adTemplateAdapter.getCount() == 1) {
                            currentAd = 0;
                        }
                        adInfo = adTemplateAdapter.getItem(currentAd);
                    } else if (isHead == 3) {
                        adInfo = adTemplateAdapterTiePian.getItem(0);
                    }
                    int type = adInfo.getAdvert_type_id();
                    if (type == Config.AdTypeCode.AD_BANNER) {
//                        isPicked = true;
                        Bitmap bitmap = ImageUtils.loadBigPic(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth / 4);
                        currentBitmap = bitmap;
                    } else if (type == Config.AdTypeCode.AD_TiePian) {
                        Bitmap bitmap = ImageUtils.loadBigPic(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth * 14 / 25);
                        currentBitmap = bitmap;
                    } else if (type == Config.AdTypeCode.AD_BIG_BANNER) {
                        Bitmap bitmap = ImageUtils.loadBigPic(path, ScreenUtils.screenWidth, ScreenUtils.screenWidth * 2 / 5);
                        currentBitmap = bitmap;
                    } else {
//                        Bitmap bitmap = ImageUtils.loadBigPic(path, ScreenUtils.dip2px(200), ScreenUtils.dip2px(200));
//                        bitmap = ImageUtils.zoomImg(bitmap, ScreenUtils.dip2px(200), ScreenUtils.dip2px(200));
                        Bitmap bitmap = ImageUtils.getSmallBitmap(path, ScreenUtils.dip2px(AdEditorActivity.this, 200), ScreenUtils.dip2px(AdEditorActivity.this, 200));
                        currentBitmap = bitmap;
//                        isPicked = true;
                    }
                    ShowCutDialog();
                    if (currentBitmap != null) {
//                    bitmap = ImageUtils.zoomImg(bitmap, 0.5f);
                        if (temp.exists()) {
                            temp.delete();
                        }
                    }
                }
                break;

            case Config.RequestCode.TEMPLETE_CHOOSE://范本获取
                if (data != null) {
                    String url = data.getStringExtra(Config.URL);
                    AdBannerInfo.AdvertDetailBean merchantArticleBannerModel = null;
                    if (isHead == 1) {
                        AdBannerInfo adInfo = adTemplateAdapterHead.getItem(currentAdHead);
                        merchantArticleBannerModel = adInfo.getAdvert_detail();
                        adInfo.setAdvert_postion(2);
                        merchantArticleBannerModel.setPic(url);
                        adTemplateAdapterHead.notifyDataSetChanged();
                    } else if (isHead == 2) {
                        if (adTemplateAdapter.getCount() == 1) {
                            currentAd = 0;
                        }
                        AdBannerInfo adInfo = adTemplateAdapter.getItem(currentAd);
                        int adTypeID = adInfo.getAdvert_type_id();
                        adInfo.setAdvert_postion(1);
                        switch (adTypeID) {
                            case 1:
                                merchantArticleBannerModel = adInfo.getAdvert_detail();
                                merchantArticleBannerModel.setPic(url);
                                adTemplateAdapter.notifyDataSetChanged();
                                break;
                        }
                    }
                }
                break;
            case AD_EDIT:
                //接收ToBusinessTempActivity 传递过来的数据
                if (data == null)
                    return;
                Bundle bundle = data.getExtras();
                bottomList = (List<AdBannerInfo>) bundle.getSerializable("bottomList");
                topList = (List<AdBannerInfo>) bundle.getSerializable("topList");
                isBottom = bundle.getBoolean("isbottom", true);

                if (isBottom) {
                    if (bottomList != null) {
                        isHead = 2;
                        way = 0;
                        swichTab(way);
                        if (bottomList.size() > 0) {
                            //底部
                            if (adTemplateAdapter != null) {
                                adTemplateAdapter.addAll(bottomList);
                                viewPager.setCurrentItem(adTemplateAdapter.getCount() - 1);
                                adTemplateAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                } else {
                    if (topList != null) {
                        way = 1;
                        isHead = 1;
                        swichTab(way);
                        if (topList.size() > 0) {
                            //顶部
                            if (adTemplateAdapterHead != null) {
                                adTemplateAdapterHead.addAll(topList);
                                adTemplateAdapterHead.notifyDataSetChanged();
                                viewPagerHead.setCurrentItem(adTemplateAdapterHead.getCount() - 1);
                            }
                        }
                    }
                }
                break;
            case AD_EDIT_BOTTOM:
                //接收ToBottomBusinessTempActivity 传递过来的数据
                if (data == null)
                    return;
                Bundle bundle2 = data.getExtras();
                bottomList = (List<AdBannerInfo>) bundle2.getSerializable("bigbottomList");
                bigbusList = (List<AdBannerInfo>) bundle2.getSerializable("bigbusList");
                if (bottomList != null) {
                    isHead = 2;
                    way = 0;
                    swichTab(way);
                    if (bottomList.size() > 0 && adTemplateAdapter != null) {
                        //底部
                        adTemplateAdapter.addAll(bottomList);
                    }
                    if (bigbusList != null && bigbusList.size() > 0) {
                        if (adTemplateAdapter != null && adTemplateAdapter.getCount() > 0 && adTemplateAdapter.getItem(0).getAdvert_type_id() == Config.AdTypeCode.AD_BIG_BANNER) {//存在大图通栏
                            adTemplateAdapter.remove(0);
                        }
                        adTemplateAdapter.add(bigbusList.get(0), 0);
                    }
                    viewPager.setCurrentItem(adTemplateAdapter.getCount() - 1);
                    adTemplateAdapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 截图弹窗
     */
    private void ShowCutDialog() {
        final AlertDialog myDialog = new AlertDialog.Builder(AdEditorActivity.this).create();
//        cropImageView = (CropImageView)myDialog.findViewById(R.id.src_pic);
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.mydialog);
//        isPicked = false;
        myDialog.getWindow()
                .findViewById(R.id.tvChoose)
                .setVisibility(View.GONE);
//                .setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
////                        ShowPickDialog(v);
//                    }
//                });
        TextView tvSure = (TextView) myDialog.findViewById(R.id.tvSure);
//        assert tvSure != null;
        if (isHead == 1) {
            currentView = adTemplateAdapterHead.getView(currentAdHead);//设置当前广告父布局
        } else if (isHead == 2) {
            currentView = adTemplateAdapter.getView(currentAd);//设置当前广告父布局
        } else if (isHead == 3) {
            currentView = adTemplateAdapterTiePian.getView(0);//设置当前广告父布局
        }
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentBitmap != null) {
                    CropView cropView = (CropView) myDialog.findViewById(R.id.src_pic);
                    Bitmap bitmap = cropView.crop();
                    int size = ImageUtils.getBitmapSize(bitmap);
//                    LogUtils.i(" iamgeSize1 ----- " + size );
                    bitmap = ImageUtils.compressBmpFromBmp(bitmap);
                    size = ImageUtils.getBitmapSize(bitmap);
//                    LogUtils.i(" iamgeSize2 ----- " + size );
                    setBitmap(bitmap, null);
                    myDialog.dismiss();
                    // FIXME: 2016/11/22 上传图片
                    byte[] pic = ImageUtils.bitmap2Bytes(bitmap);

                    /** 获取图片路径 */
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
                    byte[] b = baos.toByteArray();
                    pic = b;
                    String ad = Base64.encodeToString(pic, Base64.DEFAULT);
                    UserServiceImpl.uploadImg(AdEditorActivity.picKey, ad, String.valueOf(1), new NetworkSubscriber<UploadImgRes>() {
                        @Override
                        public int onSuccess(UploadImgRes data) {
                            super.onSuccess(data);
                            if (data != null && data.getCode() == 0) {
                                String url = data.getData().getUrl();
                                if (currentView instanceof BannerAdItem) {
                                    ((BannerAdItem) currentView).setImage(url);
                                } else if (currentView instanceof GraphicAdItem) {
                                    ((GraphicAdItem) currentView).setImage(url);
                                } else if (currentView instanceof CardAdItem) {
                                    ((CardAdItem) currentView).setImage(url);
                                } else if (currentView instanceof QRCodeAdItem) {
                                    ((QRCodeAdItem) currentView).setImage(url);
                                } else if (currentView instanceof QQAdItem) {
                                    ((QQAdItem) currentView).setImage(url);
                                } else if (currentView instanceof StoreAdItem) {
                                    ((StoreAdItem) currentView).setImage(url, resId);
                                } else if (currentView instanceof TiePianAdItem) {
                                    ((TiePianAdItem) currentView).setImage(url);
                                } else if (currentView instanceof BigAdItem) {
                                    ((BigAdItem) currentView).setImage(url);
                                }
                            } else {
                                ToastUtils.show(AdEditorActivity.this, data.getMsg());
                            }
                            return 0;
                        }
                    });
                }
            }
        });
        if (currentBitmap != null) {
            CropView cropView = (CropView) myDialog.findViewById(R.id.src_pic);
            AdBannerInfo adInfo = null;
            if (isHead == 1) {
                adInfo = adTemplateAdapterHead.getItem(0);
            } else if (isHead == 2) {
                if (currentAd > adTemplateAdapter.getCount() - 1) {
                    currentAd = 0;
                }
                adInfo = adTemplateAdapter.getItem(currentAd);
            } else if (isHead == 3) {
                adInfo = adTemplateAdapterTiePian.getItem(0);
            }
            int type = adInfo.getAdvert_type_id();
            if (type == Config.AdTypeCode.AD_BANNER) {
                cropView.setViewportWidth(ScreenUtils.screenWidth);
//                cropView.setViewportHeight(ScreenUtils.dip2px(100));
                cropView.setViewportHeight(ScreenUtils.screenWidth / 4);
            } else if (type == Config.AdTypeCode.AD_TiePian) {
                cropView.setViewportWidth(ScreenUtils.screenWidth);
                cropView.setViewportHeight(ScreenUtils.screenWidth * 14 / 25);
            } else if (type == Config.AdTypeCode.AD_BIG_BANNER) {
                cropView.setViewportWidth(ScreenUtils.screenWidth);
                cropView.setViewportHeight(ScreenUtils.screenWidth * 2 / 5);
            } else {
                cropView.setViewportWidth(ScreenUtils.dip2px(AdEditorActivity.this, 200));
                cropView.setViewportHeight(ScreenUtils.dip2px(AdEditorActivity.this, 200));
            }
            cropView.setImageBitmap(currentBitmap);
        }

        ImageView ivCancle = (ImageView) myDialog.findViewById(R.id.ivCancle);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });


    }

    /**
     * 设置图片
     *
     * @return
     */
    private void setBitmap(Bitmap bitmap, Uri uri) {


        try {
            if (bitmap != null) {


                byte[] pic = ImageUtils.bitmap2Bytes(bitmap);
                int size = ImageUtils.getBitmapSize(bitmap);
                String picExtension = "";
                /** 获取图片路径 */
                if (uri != null) {
                    String path = UriUtils.getImageAbsolutePath(this, uri);
                    picExtension = path.substring(path.lastIndexOf(".") + 1);
                } else {
//                    picExtension = FileUtils.getImageFileType(pic);
                }

                /** 截取图片后缀名 */
                AdBannerInfo info = null;
                if (isHead == 1) {
                    info = adTemplateAdapterHead.getItem(currentAdHead);
                } else if (isHead == 2) {
                    if (adTemplateAdapter.getCount() == 1) {
                        currentAd = 0;
                    }
                    info = adTemplateAdapter.getItem(currentAd);
                } else if (isHead == 3) {
                    info = adTemplateAdapterTiePian.getItem(0);
                }
                //        Bitmap bm = getSmallBitmap(filePath);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] b = baos.toByteArray();
                pic = b;
                int type = info.getAdvert_type_id();
                if (type == Config.AdTypeCode.AD_BANNER) {
                    /** 通栏广告模板设置 */
                    AdBannerInfo.AdvertDetailBean merchantArticleBannerModel = info.getAdvert_detail();
                    if (merchantArticleBannerModel == null) {
                        merchantArticleBannerModel = new AdBannerInfo.AdvertDetailBean();
                    }
                    String bannerPic = merchantArticleBannerModel.getPic();
                    info.setAdvert_detail(merchantArticleBannerModel);
                } else if (type == Config.AdTypeCode.AD_GRAPHIC) {
                } else if (type == Config.AdTypeCode.AD_CARD) {
                } else if (type == Config.AdTypeCode.AD_QR_CODE) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        JAnalyticsInterface.onPageEnd(this, "我的模板");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (currentBitmap != null && !currentBitmap.isRecycled()) {
            currentBitmap.recycle();
        }
    }
}
